//
//  CategoryViewModel.swift
//  aishop
//
//  Created by tuguowei on 2025/10/15.
//

import Foundation
import Combine

@MainActor
class CategoryViewModel: ObservableObject {
    @Published var categories: [ProductCategory] = []
    @Published var isLoading = false
    @Published var errorMessage: String?
    
    private let apiService = APIService.shared
    private var cancellables = Set<AnyCancellable>()
    
    func loadCategories() async {
        do {
            let response = try await apiService.fetchProductCategories()
            DispatchQueue.main.async {
                self.categories = response.data ?? []
            }
        } catch {
            print("加载分类失败: \(error)")
        }
    }
    
    func loadSubCategories(for categoryId: Int) async {
        do {
            let response = try await apiService.fetchThirdCategories(id: categoryId)
            DispatchQueue.main.async {
                // 更新对应分类的子分类数据
                if let index = self.categories.firstIndex(where: { $0.id == categoryId }) {
                    var updatedCategory = self.categories[index]
                    // 由于ProductCategory现在是不可变的，我们需要重新创建整个数组
                    self.categories = self.categories.map { category in
                        if category.id == categoryId {
                            return ProductCategory(
                                id: category.id,
                                pid: category.pid,
                                name: category.name,
                                icon: category.icon,
                                level: category.level,
                                sort: category.sort,
                                isShow: category.isShow,
                                childList: response.data ?? []
                            )
                        }
                        return category
                    }
                }
            }
        } catch {
            print("加载子分类失败: \(error)")
        }
    }
      
}